from stock.candlestick_charts import is_hammer,is_doji,is_star,is_medium_black_candle

def check_stock_conditions(df):
    # 确保数据列表至少有4个交易日的数据
    if len(df) < 4:
        return False,''
    last_rows = df.tail(1).iloc[0]
    _msg = ''
    if is_doji(last_rows) :
        if last_rows['open'] < last_rows['pre_close']:
            _df = df.iloc[-4:-1,]
            if is_fall_down(_df):
                return True,'十字星，下跌10%'
    if is_hammer(last_rows):
        _df = df.iloc[-4:-1,]
        if is_fall_down(_df):
            return True, '锤子线，下跌10%'
    if is_star(last_rows):
        if last_rows['open'] < last_rows['pre_close']:
            _df = df.iloc[-4:-1,]
            if is_fall_down(_df):
                return True,'星线，下跌10%'
    if is_medium_black_candle(last_rows):
        _df = df.iloc[-3:,]
        if is_fall_down(_df):
            return True, '中阴线，下跌10%'
    return False,''


def is_fall_down(df,decline_percentage = 10):
    # 初始化变量
    _negative_days = 0  # 阴线天数
    _total_drop_percentage = 0  # 4个交易日下跌总百分比
    _opening_closing_diff_sum = 0  # 每日开盘价与收盘价差的累加和
    _days = len(df)
    # 遍历数据
    for i in range(_days):
        # 计算每日的跌幅百分比
        _row = df.iloc[i]
        daily_drop_percentage = ( _row['pre_close']-_row['close']) / _row['pre_close'] * 100

        # 检查是否有3个交易日是阴线（即收盘价低于开盘价）
        if _row['close'] < _row['open']:
            _negative_days += 1

        # 累加每日的开盘价与收盘价的差值
        opening_closing_diff = abs(_row['open'] - _row['close'])
        _opening_closing_diff_sum += opening_closing_diff

        # 累加下跌总百分比
        _total_drop_percentage += daily_drop_percentage
    # 检查条件是否满足
    if _negative_days >= _days-1 and _total_drop_percentage >= decline_percentage :
        return True
    return False


